<style lang="scss" scoped>
	.container {
		// padding: R(100) 0 ;
	}


	.invitation-main {
		// background: url("../../../common/images/invitation-bg.jpg") no-repeat;
		// background-size: 100% 100%;
		position: relative;
		//   flex: 1;
		min-height: R(1600px);
		min-height: 100vh;
	}

	.invitation-main /deep/ .bg {
		position: relative;
		top: 0;
		width: 100%;
		height: 100%;
		z-index: -1;
	}

	.invitation-main-img {
		// text-align: center;
		// margin-bottom: 0.54rem;
		border: 4rpx solid #343536;
		background-color: white;
		// padding: R(20px);
		padding: 20rpx;
		display: flex;
		justify-content: center;
	}

	.invitation-main-code {
		// color: #474545;
		color: #343536;
		text-align: center;
		// font-size: 11px;
		// font-size: 0.1rem;
		font-size: 0.24rem;
		font-weight: 600;

		.code {
			color: #d8192b;
		}

		/* position: absolute;
		left: 35%; */
	}
	.invitation-main-code-name{
		display: flex;
		margin-top: R(20px);
		color: #546BB0;
		font-size: R(37px);
	}

	.invitation-main-title {
		background: url("../../../common/images/invitation-bottom.png") no-repeat;
		background-size: 100%;
		height: 50px;
		width: 300px;
		text-align: center;
		padding-top: 10px;
		color: #fff;
		font-weight: 600;
		margin-top: 45px;
		position: absolute;
		left: 50%;

		margin-left: -3rem;
	}

	.invitation-main-title span {
		color: #ff2929;
	}



	.inviter {
		margin-left: 0.2rem;
		white-space: nowrap;
		display: flex;
		flex-direction: column;
		justify-content: space-around;
	}

	.invitation-main-invitation {
		display: flex;
		flex-direction: column;
		align-items: center;

		.line {
			width: 100%;
			border-top: 1px dashed #ccc7c7;
			height: 1px;
			margin: 0.4rem auto 0.2rem;
		}

		.user-info {
			display: flex;
			white-space: nowrap;
			margin-bottom: R(60);

			.user-icon {
				width: R(120px);
				height: R(120px);
				margin-right: R(10px);
			}

			.right {
				justify-content: center;

				p:nth-child(2) {
					font-size: R(28px);
					color: #4e4e50;
				}
			}
		}

		// position: absolute;
		// right: 8%;
		// bottom: 0.1rem;
		//   padding-top: 13.7rem;
		//   padding-left: 3.8rem;
	}

	.invitation3,
	.invitation1,
	.invitation2,
	.invitation4 {
		position: absolute;
		left: 50%;
		top: 32%;
		transform: translate(-50%);
	}

	// .footer {
	//   height: 2.5rem;
	// }
	.share-box {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		padding: R(20) 0;
		background: #ffffff;
		z-index: 20;
	}

	.share-box-content {
		display: flex;
		justify-content: space-around;
	}

	.share-list {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.iconfont {
		font-size: 44px;
		color: #54eb15;
	}

	.iconfont.down {
		/* font-size: 54px; */
	}

	.btn-share {
		position: fixed;
		right: 10px;
		bottom: 100px;
		width: 40px;
		height: 40px;
		z-index: 5;

		.btn-share-icon {
			width: 100%;
			height: 100%;
			background: #fff;
			border: 1px solid #868686;
			text-align: center;
			border-radius: 50%;

			img {
				width: 35px;
				height: 35px;
				vertical-align: middle;
			}
		}
	}

	.mySwiper {
		width: 100%;
		// height: 9rem;
		margin-bottom: R(300);
		overflow: hidden !important;
	}

	.mySwiper .swiper-wrapper .swiper-slide {
		// width: 70% !important;
		border-radius: 20px;
	}

	// .mySwiper .swiper-wrapper .swiper-slide img {
	//   width: 100%;
	//   height: auto;
	//   border-radius: 20px;
	// }
	.mySwiper .swiper-wrapper .swiper-slide-prev {
		margin-top: 25px;
		height: 8rem !important;
	}

	.mySwiper .swiper-wrapper .swiper-slide-prev .bg {
		height: 8rem !important;
	}

	.mySwiper .swiper-wrapper .swiper-slide-next {
		margin-top: 25px;
		height: 8rem !important;
	}

	.mySwiper .swiper-wrapper .swiper-slide-next .bg {
		height: 8rem !important;
	}

	.mySwiper .swiper-wrapper .swiper-slide-active {
		width: 70% !important;
	}

	.bgBox {
		width: 100%;
		height: 50%;
		position: relative;
		height: R(1200px);
	}

	.bg {
		width: 100%;
		position: relative;
		height: R(1200px);
	}

	.box {
		position: absolute;
		top: R(100px);
		width: 100%;
		z-index: 1;
	}

	.erweima {
		// width: R(360) !important;
		// height: R(360) !important;
		// // border: 1px dashed #c6b9b0;
		// border-radius: 0 !important;
	}

	/* #ifdef APP-PLUS */

	// .box {
	// 	position: absolute;
	// 	top: 35%;
	// 	width: 100%;
	// 	z-index: 1;
	// }

	/* #endif */
</style>
<template>
	<div class="container">

		<div ref="myRef">
			<html2canvas ref="html2canvas" :domId="domId" @renderFinish="renderFinish">
				<div class="mySwiper" id="refBox1">
					<div class="swiper-wrapper">
						<!-- v-for="(item, index) in bannerList" :key="index" -->
						<div class="swiper-slide">
							<div>
								<div class="bgBox">
									<img class="bg" ref="bg1" mode="scaleToFill" :src="bg"></img>
								</div>
								<div class="box">
									<div class="invitation-main-invitation">
										<!-- <div class="user-info">
											<image class="user-icon" :src="user" mode="aspectFill" alt="" />
											<div class="right flex-column">
												<p>{{ codeInfo.trueName }}</p>
											</div>
										</div> -->
										<div class="invitation-main-img">
											<canvas style="height: 192px;width: 192px;" class="erweima" canvas-id="canvas"></canvas>
											<!-- <img class="erweima" :src="codeInfo.codeUrl" alt /> -->
										</div>
										<!-- <div class="line"></div> -->
										<!-- 	<div class="inviter">
										<div class="invitation-main-code">
											<p>推荐码</p>
											<p class="code">{{ codeInfo.invitationCode }}</p>
										</div>
									</div> -->
									<div class="invitation-main-code-name">
										<p>推荐人：</p>
										<p class="code">{{ codeInfo.trueName }}</p>
									</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</html2canvas>
		</div>
		<div class="share-box">
			<div class="share-box-content">
				<!-- <div class="share-list" @click="goShare('1')">
					<span class="iconfont icon-weixin"></span>
					<span>微信</span>
				</div>
				<div class="share-list" @click="goShare('2')">
					<span class="iconfont icon-pengyouquan"></span>
					<span>朋友圈</span>
				</div> -->
				<div class="share-list" @click="goShare('3')">
					<span class="iconfont icon-download down"></span>
					<span>下载图片</span>
				</div>
				<div class="share-list" @click="copyLink">
					<span class="iconfont icon-fuzhilianjielianjiefenxiang" style="color: #1296db"></span>
					<span>复制链接</span>
				</div>
			</div>
		</div>

	</div>
</template>

<script>
	import html2canvas2 from "html2canvas";
	// import Clipboard from "clipboard";
	import {
		pathToBase64,
		base64ToPath
	} from 'image-tools';
	import uQRCode from '_c/utils/uqrcode.js'
	import html2canvas from './html2canvas.vue'
	import {
		getAppConfig
	} from "_a/sms";
	export default {
		name: "Invitation",
		components: {
			html2canvas
		},
		directives: {
			// swiper: directive,
		},
		data() {
			let that = this;
			return {
				show: true, //是否显示弹框
				navBarOptions: {
					title: "邀请推客",
					router: {
						name: "home",
					},
				},
				codeInfo: {
					codeUrl: "",
					agentUser: "",
					trueName: "",
				},
				ispic: true,
				posterImg: "",
				qrCodeImg: '',
				backHeight: 700,
				isShare: false, //是否分享
				shareType: 1, //1 微信 2 朋友圈
				activeIndex2: 0,
				swiperOption: {
					direction: "horizontal",
					loop: true,
					slidesPerView: "auto",
					initialSlide: 2,
					centeredSlides: true,
					spaceBetween: 20,
					on: {
						slideChangeTransitionEnd: function() {
							// console.log("this", this, this.realIndex);
							that.activeIndex2 = this.realIndex;
							console.log("that", that.activeIndex2);
						},
					},
				},
				bannerList: [require("@/common/images/invitation/invitation-bg1.png")],
				domId: '',
				bg: '',
				user: ''
			};
		},
		async created() {
			// #ifdef APP-PLUS
			let appId = uni.getStorageSync('appId');
			console.log('配置')
			console.log(appId)
			let res = await getAppConfig({
				uniappId: appId
			})
			if (res.data && res.code == 200) {
				this.$store.commit('SETAppConfig', res.data)
			} else {
				this.$store.commit('SETAppConfig', null)
			}
			// #endif
		},
		mounted() {
			pathToBase64(require("@/common/images/invitation/invitation-bg1.png")).then(res => {
				this.bg = res
			})
			pathToBase64(require('@/common/images/user-icon.png')).then(res => {
				this.user = res
			})
			this.$nextTick(() => {
				this.getCodeHandle();
			})
		},
		computed: {
			appConfig() {
				return this.$store.getters.appConfig || null
			}
		},
		methods: {
			savePic() {
				/** 保存图片 **/
				// if (this.ispic) {
				// 	this.saveImage();
				// } else {
				this.createPoster(() => {
					this.downPic();
				})
				// }
			},
			downPic() {
				this.ispic = true;
				this.$tip.loading('保存中...');
				// console.log(this.posterImg)
				console.log(this.$isApp, this.$phoneAgent, '是否app');
				if (this.$isApp) { //this.$phoneAgent == 'android' || 
					// this.$h5Api.saveImage({
					// 	filePath: this.posterImg, //保存的图片路径，支持网络图片与base64路径
					// 	success: (path) => {
					// 		this.$toast("图片保存成功，本地路径为：\n" + path);
					// 	},
					// 	fail: (err) => {
					// 		this.$toast("保存图片失败：" + JSON.stringify(err));
					// 	},
					// });
					this.saveImg(this.posterImg)
					// this.$downloadjs(this.posterImg, '邀请码.jpg', 'image/jpg')
				} else {
					/** 其他浏览器 **/
					this.$tip.loaded()
					this.$downloadjs(this.posterImg, '邀请码.jpg', 'image/jpg')
					// this.downloadFileByBase64(this.posterImg, "邀请码.jpg");
				}

				this.closePopup();

			},
			saveImg(base64) {
				let _this = this
				console.log({base64})
				const bitmap = new plus.nativeObj.Bitmap("base64");
				_this.$tip.loaded()
				console.log(123);
				bitmap.loadBase64Data(base64, () => {
					const url = "_doc/" + new Date().getTime() + ".png";

					console.log('saveHeadImgFile', url)
					bitmap.save(url, {
						overwrite: true, // 是否覆盖
						// quality: 'quality'  // 图片清晰度
					}, (i) => {
						// 调用plus.gallery.save方法保存图片到相册
						plus.gallery.save(url, function() {
							_this.$tip.toast('图片保存', 'success')
							console.log('图片保存成功');
						}, function(error) {
							_this.$tip.toast('图片保存失败')
							console.error('图片保存失败：' + error.message);
						});

						// uni.saveImageToPhotosAlbum({
						// 	filePath: url,
						// 	success: function() {
						// 		uni.showToast({
						// 			title: '图片保存成功',
						// 			icon: 'none'
						// 		})
						// 		bitmap.clear()
						// 	}
						// });
					}, (e) => {
						uni.showToast({
							title: '图片保存失败',
							icon: 'none'
						})
						_this.$tip.toast(JSON.stringify(e))
						bitmap.clear()
					});
				}, (e) => {
					uni.showToast({
						title: '图片保存失败',
						icon: 'none'
					})
					_this.$tip.toast(JSON.stringify(e))
					bitmap.clear()
				});
			},
			// 渲染成功!
			renderFinish(filePath) {
				// console.log(filePath);
				this.posterImg = filePath;
				// this.saveImg()

				// console.log("filePath", filePath)
			},
			/**
			 *
			 * */
			copyLink() {
				let agentNo = this.$store.getters.user.agentNo;
				let message
				// #ifdef H5
				message = `${window.location.origin}/pages/login/register?agentNo=${agentNo}`;
				// #endif
				
				// #ifdef APP-PLUS
				if(this.appConfig) {
					message = `https://${this.appConfig.appDomain}/pages/login/register?agentNo=${agentNo}`;
				}else{
					message = `${this.$config.origin}/pages/login/register?agentNo=${agentNo}`;
				}
				// #endif
				this.$copy(message)
			},
			//调起pop弹框
			showPopup() {
				this.show = true;
			},
			//关闭弹窗
			closePopup() {
				this.show = false;
			},
			getCodeHandle() {
				// console.log('配置')
				// console.log(this.appConfig)
				
				let _this = this
				this.$tip.loading('二维码正在生成中...');
				let agentNo = this.$store.getters.user.agentNo;
				this.codeInfo.trueName = this.$store.getters.user.agentName;
				// console.log(this.$config.origin)
				let message
				// #ifdef H5
				message = `${window.location.origin}/pages/login/register?agentNo=${agentNo}`;
				// #endif
				// #ifdef APP-PLUS
				if(this.appConfig) {
					message = `https://${this.appConfig.appDomain}/pages/login/register?agentNo=${agentNo}`;
				}else{
					message = `${this.$config.origin}/pages/login/register?agentNo=${agentNo}`;
				}
				// #endif
				console.log("message", message);
				uQRCode.make({
					canvasId: 'canvas',
					text: message,
					size: 192,
					// margin: 10,
					success: res => {
						_this.qrCodeImg = res
					},
					complete: () => {
						_this.$tip.loaded();
						// uni.hideLoading()
					}
				}) //170

			},
			//分享按钮点击执行
			goShare(type) {
				if (type == 3) {
					// 下载图片
					this.savePic()
					this.isShare = false;
				} else {
					this.isShare = true;
					this.shareType = type;
					// this.saveImage();
					this.share()
				}

			},
			// 生成海报
			createPoster(fun) {
				console.log(!this.$isApp);
				// #ifdef H5
				if (!this.isShare) {

					if (!this.posterImg) {
						this.domId = '#refBox1'
					}
				}
				// #endif
				// #ifdef APP-PLUS
				if (!this.posterImg) {
					this.domId = '#refBox1'
				}
				// #endif
				// 没有生成过
				setTimeout(() => {
					fun()
				}, 1500)
			},
			downLoad() {
				// #ifdef APP-PLUS
				const downloadTask = plus.downloader.createDownload(url, {
					timeout: 0, //下载任务超时时间，如果设置为0则表示永远不超时
					filename: '_doc/download/'
				}, (d, status) => {
					if (status === 200) {
						const path = plus.io.convertLocalFileSystemURL(d.filename)
						// 处理下载成功的逻辑
						console.log('下载成功', path);
						plus.gallery.save(path, function() {
							console.log('视频已保存到相册');
						}, function(error) {
							console.log('保存视频到相册失败: ' + error.message);
						});
						downloadTask.abort();

					} else {
						// 下载失败
						// 处理下载失败的逻辑
						console.log('下载失败');
					}

				});
				downloadTask.start();

				downloadTask.addEventListener('statechanged', (task, status) => {
					switch (task.state) {
						case 2: // 开始
							console.log('开始下载');

							break;
						case 3: // 正在下载，更新下载进度
							console.log('下载进度', task.downloadedSize / task.totalSize);

							break;
						case 4: // 下载完成

							console.log('下载完成');
							break;
					}
				});
				// #endif

			},
			share() {
				// console.log("this.posterImg", this.posterImg);
				let agentNo = this.$store.getters.user.agentNo;
				let url
				// #ifdef H5
				url = `${window.location.origin}/pages/login/register?agentNo=${agentNo}`;
				this.$tip.toast('暂不支持!')
				// #endif
				// #ifdef APP-PLUS
				// 生成海报
				url = `${this.$config.origin}/pages/login/register?agentNo=${agentNo}`;
				this.createPoster(() => {
					uni.share({
						provider: "weixin",
						scene: this.shareType == '1' ? "WXSceneSession" : 'WXSceneTimeline',
						type: '0',
						href: url,
						title: this.shareType == '1' ? "收款宝展业版" : '收款宝展业版，助力平凡人的创业平台',
						summary: "收款宝展业版诚邀您加入,轻松做代理!",
						imageUrl: this.posterImg,
						success: function(res) {
							console.log("success:" + JSON.stringify(res));
						},
						fail: function(err) {
							console.log("fail:" + JSON.stringify(err));
						}
					});
				})

				// #endif


				//分享所需相关参数




			},
			/*保存图片的方法（即按钮点击触发的方法）
						第一个参数为需要保存的div的id名
						第二个参数为保存图片的名称 */
			saveImage() {
				// let canvasID = this.$refs[divText];
				// html2canvas(canvasID).then(canvas => {
				// 	let link = document.createElement("a");
				// 	link.href = canvas.toDataURL();//下载链接
				// 	link.setAttribute("download",imgText);
				// 	link.style.display = "none";//a标签隐藏
				// 	document.body.appendChild(link);
				// 	link.click();
				// });
				// 生成海报
				// window.pageYoffset = 0;
				// document.documentElement.scrollTop = 0;
				// document.body.scrollTop = 0;
				const that = this;
				// let w = that.$refs.invitationMainRef.offsetWidth - 1;
				// let h = that.$refs.invitationMainRef.offsetHeight;
				let scale = 2.75; //放大倍数2
				// let w = that.$refs.myRef.offsetWidth - 1;
				// let h = that.$refs.myRef.offsetHeight;
				;
				// console.log("arr", arr);
				let w = this.$refs.refBox1.offsetWidth;
				let h = this.$refs.refBox1.offsetHeight;
				// console.log(JSON.stringify(this.$refs.refBox1.$el))


				console.log(this.isShare)
				html2canvas2(document.getElementById('refBox1'), {
					dpi: 160,
					scale: scale,
					useCORS: true,
					allowTaint: false,
					taintTest: true, //是否在渲染前测试图片
					logging: false,
					letterRendering: true,
					width: w, //显示的canvas窗口的宽度
					height: h, //显示的canvas窗口的高度
				}).then((canvas) => {
					// 在微信里,可长按保存或转发
					console.log("canvas", canvas);
					canvas.getContext("2d");

					console.log(canvas.toDataURL("image/png"));

					if (that.isShare) {
						//如果是分享则调用分享方法
						that.share();
						return false;
					}
					setTimeout(() => {
						that.ispic = false;
						that.downPic();
					}, 500);
				})
				// console.log("w", w, h);
				// that.$refs.invitationMainRef
				//  that.$refs.myRef

			},

			dataURLtoBlob(dataurl) {
				var arr = dataurl.split(","),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new Blob([u8arr], {
					type: mime,
				});
			},
			downloadFile(url, name) {
				var a = document.createElement("a");
				a.setAttribute("href", url);
				a.setAttribute("download", name);
				a.setAttribute("target", "_blank");
				let clickEvent = document.createEvent("MouseEvents");
				clickEvent.initEvent("click", true, true);
				a.dispatchEvent(clickEvent);
				this.$tip.toast('下载成功!')
			},
			downloadFileByBase64(base64, name) {

				// this.posterImg = res.data;
				// this.downloadFile(this.posterImg, name);

				var myBlob = this.dataURLtoBlob(base64)
				var myUrl = URL.createObjectURL(myBlob)
				console.log(myUrl)
				this.downloadFile(myUrl, name)
			},
		},
	};
</script>